package admin

import (
	"invitation/internal/application"
	"invitation/internal/http/middleware"
	"invitation/internal/model"
	"invitation/internal/pojo/dto"

	"github.com/gofiber/fiber/v2"
)

func CreateGameEndpoint(application *application.Application) func(ctx *fiber.Ctx) error {
	return func(ctx *fiber.Ctx) error {
		gameReq := ctx.Locals(middleware.LocalKeysGameCreateRequest).(*dto.GamePayload)
		if gameReq.Name == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "name is required",
			})
		}
		if gameReq.Introduction == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "introduction is required",
			})
		}
		if gameReq.TheoryExplanation == "" {
			return ctx.Status(400).JSON(fiber.Map{
				"message": "theory is required",
			})
		}
		txCtx, err := application.RepoManager().BeginTx(ctx.Context())
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		defer func() {
			if err != nil {
				application.RepoManager().RollbackTx(txCtx)
			} else {
				application.RepoManager().CommitTx(txCtx)
			}
		}()
		gameInfo := &model.GameInfo{
			Name:           gameReq.Name,
			ProblemToSolve: gameReq.ProblemToSolve,
			Desc:           gameReq.Desc,
		}
		gameInfoID, err := application.RepoManager().GameInfoRepo().Create(gameInfo)
		if err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := application.RepoManager().GameIntroductionRepo().Create(gameInfoID, gameReq.Introduction); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		if err := application.RepoManager().GameTheoryRepo().Create(gameInfoID, gameReq.TheoryExplanation); err != nil {
			return ctx.Status(500).JSON(fiber.Map{
				"message": err.Error(),
			})
		}
		return ctx.Status(200).JSON(fiber.Map{
			"message": "success",
		})
	}
}
